package com.species.web.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baidu.aip.imageclassify.AipImageClassify;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.system.domain.vo.ImageClassifyVo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author DRIES
 */
public class BaiduYunConfig {

    //设置APPID/AK/SK
    public static final String APP_ID = "25861990";
    public static final String API_KEY = "sS5O2ygZ9oytPVVn9bZcGGpP";
    public static final String SECRET_KEY = "ZgreAxWczzqRPHE1GsP5Wt0rSWGtd0QM";

    public static List<ImageClassifyVo> aipImageClassify(MultipartFile file, String type) throws IOException {
        // 初始化一个AipImageClassify
        AipImageClassify client = new AipImageClassify(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
        // client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
        // client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<>();
        options.put("baike_num", "5");
        // options.put("top_num", "3");
        // options.put("baike_num", "5");

        JSONObject res = new JSONObject();
        // byte[] bytes = FileUtil.readBytes(file);
        if ("animal".equals(type)) {
            // 参数为二进制数组
            res = client.animalDetect(file.getBytes(), options);
        }
        if ("plant".equals(type)) {
            // 参数为二进制数组
            res = client.plantDetect(file.getBytes(), options);
        }

        List<ImageClassifyVo> imageClassifyVos = null;
        if (res.has("result")) {
            JSONArray resultArr = res.getJSONArray("result");
            String resultStr = resultArr.toString();
            imageClassifyVos = JSONUtil.toList(resultStr, ImageClassifyVo.class);
        }

        return imageClassifyVos;
    }


}
